package com.guodi.map.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.common.utils.PageData;
import com.guodi.common.utils.ReadFileUtil;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.tool.utils.CollectionUtil;
import com.guodi.map.constant.MapConst;
import com.guodi.map.dto.MapDivisionTOLayerDto;
import com.guodi.map.entity.MapDivision;
import com.guodi.map.entity.MapLayer;
import com.guodi.map.mapper.MapDivisionMapper;
import com.guodi.map.service.IMapDivisionService;
import com.guodi.map.service.IMapLayerService;
import com.guodi.map.utils.RecursionUtil;
import com.guodi.common.utils.RepalceDXYUrlUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @描述：行政区划表 服务类
 * @作者: 代鹏刚
 * @日期: 2020-04-07
 */
@Service
public class MapDivisionServiceImpl extends ServiceImpl<MapDivisionMapper, MapDivision> implements IMapDivisionService {

    @Resource
    private MapDivisionMapper mapDivisionMapper;
    @Autowired
    public IMapDivisionService mapDivisionService;
    @Autowired
    private IMapLayerService mapLayerService;

    @Override
    public List<MapDivision> listByEntity(MapDivision mapDivision) {
        List<MapDivision> mapDivisions = this.list();
        for (MapDivision obj:mapDivisions) {
            MapLayer mapLayer = mapLayerService.getById(obj.getLayerId());
            if(mapLayer!=null && mapLayer.getReleaseType().equals(MapConst.MAP_SERVICE_TYPE_ARCGIS)){
                obj.setLayerUrl(mapLayer.getLayerUrl()+"/"+mapLayer.getLayerTable());
            } else if(mapLayer!=null) {
                obj.setLayerUrl(mapLayer.getLayerUrl());
            }
        }
        return mapDivisions;
    }

    @Override
    public List<MapDivision> listDivisionTree() {
        List<MapDivision> mapDivisionRootList = mapDivisionMapper.listRootdivision();
        List<MapDivision> mapDivisionAllList = mapDivisionMapper.allList();
        return RecursionUtil.recursiveData(mapDivisionRootList, mapDivisionAllList);
    }

    @Override
    public List<MapDivision> listDivisionTreeData(List<String> parentIds) {
        if (parentIds == null || parentIds.isEmpty()) {
            return null;
        }
        List<MapDivision> mapDivisions = mapDivisionMapper.listDivisionTreeData(parentIds);
        if (mapDivisions == null) {
            return null;
        }
        for (MapDivision mapDivision : mapDivisions) {
            //是否是最后一级节点
            boolean isLastLevel = true;
            for (MapDivision mapDivision2 : mapDivisions) {
                if (mapDivision.getParentCode().equals(mapDivision2.getCode())) {
                    mapDivision.setParentId(mapDivision2.getId());
                }
                if (mapDivision.getCode().equals(mapDivision2.getParentCode())) {
                    isLastLevel = false;
                }
                if (mapDivision.getParentId() == null) {
                    mapDivision.setParentId("-1");
                }
            }
            if (isLastLevel) {
                mapDivision.setType("2");
            } else {
                mapDivision.setType("1");
            }
        }
        return mapDivisions;
    }

    @Override
    public void importLayer(PageData pd) {
        LambdaQueryWrapper<MapDivision> wrapper = new QueryWrapper().lambda();
        try {
            List<MapDivision> mapDivisionList = new ArrayList<>();
            //一级行政区划
            if (pd.get("one_layer_url") != null && pd.getString("one_layer_url").trim().length() > 0) {
                //获取行政区划数据
                List<MapDivision> layerData = getLayerData(pd.getString("one_layer_id"), pd.getString("one_layer_url"), pd.getString("one_field_code"), pd.getString("one_field_name"));
                mapDivisionList.addAll(layerData);
            }
            //二级行政区划
            if (pd.get("two_layer_url") != null && pd.getString("two_layer_url").trim().length() > 0) {
                //获取行政区划数据
                List<MapDivision> layerData = getLayerData(pd.getString("two_layer_id"), pd.getString("two_layer_url"), pd.getString("two_field_code"), pd.getString("two_field_name"));
                mapDivisionList.addAll(layerData);
            }
            //三级行政区划
            if (pd.get("three_layer_url") != null && pd.getString("three_layer_url").trim().length() > 0) {
                //获取行政区划数据
                List<MapDivision> layerData = getLayerData(pd.getString("three_layer_id"), pd.getString("three_layer_url"), pd.getString("three_field_code"), pd.getString("three_field_name"));
                mapDivisionList.addAll(layerData);
            }
            //四级行政区划
            if (pd.get("four_layer_url") != null && pd.getString("four_layer_url").trim().length() > 0) {
                //获取行政区划数据
                List<MapDivision> layerData = getLayerData(pd.getString("four_layer_id"), pd.getString("four_layer_url"), pd.getString("four_field_code"), pd.getString("four_field_name"));
                mapDivisionList.addAll(layerData);
            }
            // 设置各个行政区划的父节点（兼容6位和12位行政区划代码）
            for (int i = 0; i < mapDivisionList.size(); i++) {
                MapDivision mapDivision = mapDivisionList.get(i);
                String code = mapDivision.getCode();
                String parentCode = getParentCode(code);
                for (int j = 0; j < mapDivisionList.size(); j++) {
                    MapDivision mapDivision1 = mapDivisionList.get(j);
                    String code1 = mapDivision1.getCode();
                    //去掉后面的0
                    code1 = code1.replaceAll("0+$", "");
                    // 如果长度不是（2 4 6 9 12）说明行政区划多去0了 补0
                    if(code1.length()!=2 &&code1.length()!=4 &&code1.length()!=6 &&code1.length()!=9 && code1.length()!=12){
                        code1 = code1 + "0";
                    }
                    if(parentCode.equals(code1)){
                        parentCode = mapDivision1.getCode();
                    }
                }
                //String parentCode = formatParentCode(code);
                mapDivision.setParentCode( parentCode);
            }
            if(!mapDivisionList.isEmpty()){
                // 导入之前清空“行政区划表”数据
                mapDivisionService.remove(wrapper);
                // 保存
                mapDivisionService.saveBatch(mapDivisionList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
    * @描述:获取去掉后面0的父行政区划代码
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/6/11 14:59
    **/
    public String getParentCode(String code) {
        String parentCode = "-1";
        //去掉后面的0
        code = code.replaceAll("0+$", "");
        //2 4 6 9 12  （省、市、县、乡、村委）
        //如果编码大于9为12位属于居村委
        if (code.length() > 9) {
            //当前节点是村委，它的上级节点为9位的乡镇
            parentCode = code.substring(0, 9);
        } else if (code.length() > 6) {
            //当前节点是乡镇，它的上级节点为6位的区县
            parentCode = code.substring(0, 6);
        } else if (code.length() > 4) {
            //当前节点为区县，它的上级节点为4位的区市
            parentCode = code.substring(0, 4);
        } else if (code.length() > 2) {
            //当前节点为市，它的上级节点为2位的省
            parentCode = code.substring(0, 2);
        }
        return parentCode;
    }

    /**
     * @描述:获取父行政区划代码，补充为6位、9位或12位
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2020/12/14
     **/
    public String formatParentCode(String code) {
        String parentCode = "-1";
        //2 4 6 9 12  （省、市、县、乡、村委）
        //如果编码大于9为12位属于居村委
        if (code.length() > 9) {
            //当前节点是村委，它的上级节点为9位的乡镇
            parentCode = code.substring(0, 9);
        } else if (code.length() > 6) {
            //当前节点是乡镇，它的上级节点为6位的区县
            parentCode = code.substring(0, 6);
        } else if (code.length() > 4) {
            //当前节点为区县，它的上级节点为4位的区市
            parentCode = code.substring(0, 4)  + "00";
        } else if (code.length() > 2) {
            //当前节点为市，它的上级节点为2位的省
            parentCode = code.substring(0, 2) + "0000";
        }
        return parentCode;
    }

    @Override
    public void importSuLayer(PageData pd) {
        LambdaQueryWrapper<MapDivision> wrapper = new QueryWrapper().lambda();
        try {
            //导入之前清空“行政区划表”数据
            mapDivisionService.remove(wrapper);
            //一级行政区划
            if (pd.get("one_layer_url") != null && pd.getString("one_layer_url").trim().length() > 0) {
                //保存图层数据
                saveSuLayerData(pd.getString("one_layer_id"), pd.getString("one_layer_name"), pd.getString("one_layer_url"), pd.getString("one_field_code"), pd.getString("one_field_name"), pd.getString("one_field_parent_code"));
            }
            //二级行政区划
            if (pd.get("two_layer_url") != null && pd.getString("two_layer_url").trim().length() > 0) {
                //保存图层数据
                saveSuLayerData(pd.getString("two_layer_id"), pd.getString("two_layer_name"), pd.getString("two_layer_url"), pd.getString("two_field_code"), pd.getString("two_field_name"), pd.getString("two_field_parent_code"));
            }
            //三级行政区划
            if (pd.get("three_layer_url") != null && pd.getString("three_layer_url").trim().length() > 0) {
                //保存图层数据
                saveSuLayerData(pd.getString("three_layer_id"), pd.getString("three_layer_name"), pd.getString("three_layer_url"), pd.getString("three_field_code"), pd.getString("three_field_name"), pd.getString("three_field_parent_code"));
            }
            //四级行政区划
            if (pd.get("four_layer_url") != null && pd.getString("four_layer_url").trim().length() > 0) {
                //保存图层数据
                saveSuLayerData(pd.getString("four_layer_id"), pd.getString("four_layer_name"), pd.getString("four_layer_url"), pd.getString("four_field_code"), pd.getString("four_field_name"), pd.getString("four_field_parent_code"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importSuLayer(MapDivisionTOLayerDto dto) {
        LambdaQueryWrapper<MapDivision> wrapper = new QueryWrapper().lambda();
        try {
            //导入之前清空“行政区划表”数据
            mapDivisionService.remove(wrapper);
            //一级行政区划
            if (StringUtils.isNotEmpty(dto.getOne_layer_url())) {
                //保存图层数据
                saveSuLayerData(dto.getOne_layer_id(), dto.getOne_layer_name(), dto.getOne_layer_url(), dto.getOne_field_code(), dto.getOne_field_name(), dto.getOne_field_parent_code());
            }
            //二级行政区划
            if (StringUtils.isNotEmpty(dto.getTwo_layer_url())) {
                //保存图层数据
                saveSuLayerData(dto.getTwo_layer_id(), dto.getTwo_layer_name(), dto.getTwo_layer_url(), dto.getTwo_field_code(), dto.getTwo_field_name(), dto.getTwo_field_parent_code());
            }
            //三级行政区划
            if (StringUtils.isNotEmpty(dto.getThree_layer_url())) {
                //保存图层数据
                saveSuLayerData(dto.getThree_layer_id(), dto.getThree_layer_name(), dto.getThree_layer_url(), dto.getThree_field_code(), dto.getThree_field_name(), dto.getThree_field_parent_code());
            }
            //四级行政区划
            if (StringUtils.isNotEmpty(dto.getFour_layer_url())) {
                //保存图层数据
                saveSuLayerData(dto.getFour_layer_id(), dto.getFour_layer_name(), dto.getFour_layer_url(), dto.getFour_field_code(), dto.getFour_field_name(), dto.getFour_field_parent_code());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送Post Json数据格式
     *
     * @param url
     * @param data
     * @return
     */
    public static String sendPost2(String url, String data) {
        String response = null;

        try {
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                String newUrl = RepalceDXYUrlUtil.repalceDXYUrl(url);
                HttpPost httppost = new HttpPost(newUrl);
                StringEntity stringentity = new StringEntity(data,
                        ContentType.create("application/json", "UTF-8"));
                httppost.setEntity(stringentity);
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils
                        .toString(httpresponse.getEntity());

            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 保存SuperMap服务图层信息
     *
     * @param layerId
     * @param layerName
     * @param layerUrl
     * @param fieldCode
     * @param fieldName
     * @param fieldParentCode
     */
    public void saveSuLayerData(String layerId, String layerName, String layerUrl, String fieldCode, String fieldName, String fieldParentCode) {
        //获取查询的图层名称
//        String layerInfoUrl =layerUrl +"/layers.json";
//        String jsonStr1  = ReadFileUtil.getJsonByUrl(layerInfoUrl).trim();
//        JSONArray jsonArray = JSONArray.fromObject(jsonStr1);
//        JSONObject jsonMap = (JSONObject) jsonArray.get(0);
//        JSONObject subLayers = jsonMap.getJSONObject("subLayers");
//        JSONArray layers = subLayers.getJSONArray("layers");
//        JSONObject datasetInfo = layers.getJSONObject(0).getJSONObject("datasetInfo");
//        //获取图层名称
//        String layerName1 = (String) datasetInfo.get("name");
//        String dataSourceName1 = (String) datasetInfo.get("dataSourceName");
//        String cx_layerName = layerName1 +"@"+dataSourceName1;
        Map<String, Object> leftBottom = new HashMap<>();
        leftBottom.put("x", 0);
        leftBottom.put("y", 0);
        Map<String, Object> rightTop = new HashMap<>();
        rightTop.put("x", 100);
        rightTop.put("y", 100);
        Map<String, Object> bounds = new HashMap<>();
        bounds.put("leftBottom", leftBottom);
        bounds.put("rightTop", rightTop);
        Map<String, Object> queryParameters = new HashMap<>();
        ArrayList<Map> queryParams = new ArrayList<>();
        Map<String, Object> queryParams1 = new HashMap<>();
        queryParams1.put("attributeFilter", "SMID &gt; 0");
        queryParams1.put("name", layerName);
        queryParams.add(queryParams1);
        queryParameters.put("queryParams", queryParams);
        queryParameters.put("startRecord", 0);
        queryParameters.put("expectCount", 0);
        queryParameters.put("networkType", "LINE");
        queryParameters.put("queryOption", "ATTRIBUTE");
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("queryMode", "SqlQuery");
        jsonParam.put("bounds", bounds);
        jsonParam.put("distance", 1);
        jsonParam.put("queryParameters", queryParameters);
        jsonParam.put("keywords", "");
        jsonParam.put("spatialQueryMode", "INTERSECT");
        String url = layerUrl + "/queryResults.json?returnPostAction=true&getMethodForm=true&returnContent=true";
        String param = jsonParam.toString();
        try {
            //查询获取图层字段值集合
            String jsonStr = sendPost2(url, param);
            JSONObject jsonObj = JSONObject.fromObject(jsonStr);
            MapDivision mapDivision = new MapDivision();
            //获取图层字段值集合
            JSONArray recordsets = jsonObj.getJSONArray("recordsets");
            JSONObject recordsetsMap = recordsets.getJSONObject(0);
            JSONArray featuresArray = recordsetsMap.getJSONArray("features");
            //是否是12位的区县编码格式
            boolean b = true;
            // 如果所有code都是12位 说明是地理编码采用的是12位的
            for (int i = 0; i < featuresArray.size(); i++) {
                JSONObject featuresJson = featuresArray.getJSONObject(i);
                //获取字段值对象
                //JSONObject fieldObj = featuresJson.getJSONObject("attributes");
                JSONArray fieldNames =  (JSONArray) featuresJson.get("fieldNames");
                JSONArray fieldValues = (JSONArray) featuresJson.get("fieldValues");
                //添加“行政区划”数据
                mapDivision.setId(UuidUtil.get32UUID());
                //获取图层编码
                //String code = fieldObj.get(fieldCode) == null ? "":fieldObj.get(fieldCode).toString();
                int sy = getIndex(fieldNames,fieldCode);
                String code =fieldValues.get(sy).toString();
                if (code != null && code.length() < 12) {
                    b = false;
                }
            }
            for (int i = 0; i < featuresArray.size(); i++) {
                JSONObject featuresJson = featuresArray.getJSONObject(i);
                //获取字段值对象
                // JSONObject fieldObj = featuresJson.getJSONObject("attributes");
                JSONArray fieldNames =  (JSONArray) featuresJson.get("fieldNames");
                JSONArray fieldValues = (JSONArray) featuresJson.get("fieldValues");
                //添加“行政区划”数据
                mapDivision.setId(UuidUtil.get32UUID());
                //获取图层编码
                //String code = fieldObj.get(fieldCode) == null ? "":fieldObj.get(fieldCode).toString();
                int sy = getIndex(fieldNames,fieldCode);
                String code =fieldValues.get(sy).toString();
                mapDivision.setCode(code);
                mapDivision.setName(fieldValues.get(getIndex(fieldNames,fieldName)).toString());
                //默认为-1，属于省级
                String parentCode = "-1";
                //如果导入图层是，没有配置上级编码字段，则自动根据编码截取上级编码
                if (fieldParentCode == null || fieldParentCode.trim().length() == 0) {
                    //去掉后面的0
                    code = code.replaceAll("0+$", "");
                    //2 4 6 9 12  （省、市、县、乡、村委）
                    if (code.length() > 12){
                        parentCode = code.substring(0, 12);
                    } else if (code.length() > 9) {
                        //村委
                        parentCode = code.substring(0, 9);
                    } else if (code.length() > 6) {
                        //乡镇
                        parentCode = code.substring(0, 6);
                    } else if (code.length() > 4) {
                        //县
                        parentCode = code.substring(0, 4);
                    } else if (code.length() > 2) {
                        //市
                        parentCode = code.substring(0, 2);
                    }
                    //如果是采用12位的方式 补0补够12
//                    if (b) {
//                        int codeLen = code.length();
//                        int parentCodeLen = parentCode.length();
//                        while (codeLen < 12) {
//                            code = code + '0';
//                            codeLen = codeLen + 1;
//                        }
//                        while (parentCodeLen < 12 && !parentCode.equals("-1")) {
//                            parentCode = parentCode + '0';
//                            parentCodeLen = parentCodeLen + 1;
//                        }
//                    }


                } else {
                    parentCode = fieldValues.get(fieldNames.indexOf(fieldParentCode)).toString();
                }
                mapDivision.setParentCode(parentCode);
                mapDivision.setLayerId(layerId);
                mapDivision.setCodeField(fieldCode);
                //保存
                mapDivisionService.save(mapDivision);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
    * @描述:获取图层数据
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/6/11 14:20
    **/
    public List<MapDivision> getLayerData(String layerId, String layerUrl, String fieldCode, String fieldName){
        // 查询行政区划数量是否超过1000（如果超过则循环查询）
        String newUrl = layerUrl + "/query?where=1=1&returnIdsOnly=true&f=pjson";
        String objectIdStr = JSONObject.fromObject(ReadFileUtil.getStringByUrl(newUrl)).getString("objectIds");
        String[] objectIds = objectIdStr.substring(1, objectIdStr.length() - 1).split(",");

        // 存储查询行政区划数据集
        JSONArray featuresArray = new JSONArray();
        // 查询条件
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("where", "1=1");
        paramMap.put("outFields", "*");
        paramMap.put("returnGeometry", "false");
        paramMap.put("spatialRel", "esriSpatialRelIntersects");
        paramMap.put("geometryType", "esriGeometryEnvelope");
        paramMap.put("returnIdsOnly", "false");
        paramMap.put("returnCountOnly", "false");
        paramMap.put("returnZ", "false");
        paramMap.put("returnM", "false");
        paramMap.put("returnDistinctValues", "false");
        paramMap.put("f", "pjson");

        // 当行政区划数量超出1000时进行循环查询
        if (objectIds != null && objectIds.length > 1000) {
            int page = objectIds.length / 1000 + (objectIds.length % 1000 == 0 ? 0 : 1);
            for (int j = 1; j <= page; j++) {
                StringBuffer objectIdBuffer = new StringBuffer();
                for (int k = (j - 1) * 1000; k < (j * 1000 > objectIds.length ? objectIds.length : j * 2); k++) {
                    objectIdBuffer.append(objectIds[k]).append(",");
                }
                paramMap.put("where", "OBJECTID in (" + objectIdBuffer.toString().substring(0, objectIdBuffer.toString().length()-1) + ")");
                // 查询获取图层数据集
                JSONArray newFeaturesArray = JSONObject.fromObject(ReadFileUtil.getStringByUrl(layerUrl + "/query", paramMap)).getJSONArray("features");
                featuresArray.addAll(newFeaturesArray);
            }
        } else {
            // 查询获取图层数据集
            featuresArray = JSONObject.fromObject(ReadFileUtil.getStringByUrl(layerUrl + "/query", paramMap)).getJSONArray("features");
        }

        // 存储要新增的行政区划对象集合
        List<MapDivision> mapDivisionList = new ArrayList<>();
        for (int i = 0; i < featuresArray.size(); i++) {
            JSONObject featuresJson = featuresArray.getJSONObject(i);
            // 获取字段值对象
            JSONObject fieldObj = featuresJson.getJSONObject("attributes");
            MapDivision mapDivision = new MapDivision();
            // 添加“行政区划”数据
            mapDivision.setId(UuidUtil.get32UUID());
            // 获取图层编码
            String code = fieldObj.get(fieldCode) == null ? "" : fieldObj.get(fieldCode).toString();
            mapDivision.setCode(code);
            mapDivision.setName(fieldObj.get(fieldName).toString());
            mapDivision.setLayerId(layerId);
            mapDivision.setCodeField(fieldCode);
            // mapDivision.setFeatures(featuresJson.toString());
            // 保存
            mapDivisionList.add(mapDivision);
        }
        return mapDivisionList;
    }

    /**
     * @描述: 保存图层数据
     * @作者: 代鹏刚
     * @日期: 2020/4/8 15:29
     **/
    public void saveLayerData(String layerId, String layerName, String layerUrl, String fieldCode, String fieldName, String fieldParentCode) {
        String queryWhere = "/query?where=1=1&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&returnIdsOnly=false&returnCountOnly=false&returnZ=false&returnM=false&returnDistinctValues=false&f=pjson";
        String url = "";
        try {
            if (layerUrl.indexOf("?") != -1) {
                //截取url参数字符串
                String layerWhere = layerUrl.substring(layerUrl.indexOf("?") + 1);
                //重新拼接url地址
                url = layerUrl.substring(0, layerUrl.indexOf("?")) + queryWhere + "&" + layerWhere;
            } else {
                url = layerUrl + queryWhere;
            }
            //查询获取图层字段值集合
            String jsonStr = ReadFileUtil.getStringByUrl(url).trim();
            JSONObject jsonObj = JSONObject.fromObject(jsonStr);
            MapDivision mapDivision = new MapDivision();
            //获取图层字段值集合
            JSONArray featuresArray = jsonObj.getJSONArray("features");
            //是否是12位的区县编码格式
            boolean b = true;
            // 如果所有code都是12位 说明是地理编码采用的是12位的
            for (int i = 0; i < featuresArray.size(); i++) {
                JSONObject featuresJson = featuresArray.getJSONObject(i);
                //获取字段值对象
                JSONObject fieldObj = featuresJson.getJSONObject("attributes");
                //添加“行政区划”数据
                mapDivision.setId(UuidUtil.get32UUID());
                //获取图层编码
                String code = fieldObj.get(fieldCode) == null ? "" : fieldObj.get(fieldCode).toString();
                if (code != null && code.length() < 12) {
                    b = false;
                }
            }
            for (int i = 0; i < featuresArray.size(); i++) {
                JSONObject featuresJson = featuresArray.getJSONObject(i);
                //获取字段值对象
                JSONObject fieldObj = featuresJson.getJSONObject("attributes");
                //添加“行政区划”数据
                mapDivision.setId(UuidUtil.get32UUID());
                //获取图层编码
                String code = fieldObj.get(fieldCode) == null ? "" : fieldObj.get(fieldCode).toString();
                mapDivision.setCode(code);
                mapDivision.setName(fieldObj.get(fieldName).toString());
                //默认为-1，属于省级
                String parentCode = "-1";
                //如果导入图层是，没有配置上级编码字段，则自动根据编码截取上级编码
                if (fieldParentCode == null || fieldParentCode.trim().length() == 0) {
                    //去掉后面的0
                    code = code.replaceAll("0+$", "");
                    //2 4 6 9 12  （省、市、县、乡、村委）
                    //如果编码大于9为12位属于居村委
                    if (code.length() > 9) {
                        //村委
                        parentCode = code.substring(0, 9);
                    } else if (code.length() > 6) {
                        //乡镇
                        parentCode = code.substring(0, 6);
                    } else if (code.length() > 4) {
                        //县
                        parentCode = code.substring(0, 4);
                    } else if (code.length() > 2) {
                        //市
                        parentCode = code.substring(0, 2);
                    }
                    //如果是采用12位的方式 补0补够12
                    if (b) {
                        int codeLen = code.length();
                        int parentCodeLen = parentCode.length();
                        while (codeLen < 12) {
                            code = code + '0';
                            codeLen = codeLen + 1;
                        }
                        while (parentCodeLen < 12 && !parentCode.equals("-1")) {
                            parentCode = parentCode + '0';
                            parentCodeLen = parentCodeLen + 1;
                        }
                    }
                } else {
                    parentCode = fieldObj.getString(fieldParentCode);
                }
                mapDivision.setParentCode(parentCode);
                mapDivision.setLayerId(layerId);
                mapDivision.setCodeField(fieldCode);
                //保存
                mapDivisionService.save(mapDivision);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取元素在数组索引位置
     *
     * @param arr
     * @param value
     * @return
     */
    public int getIndex(JSONArray arr, String value) {
        for (int i = 0; i < arr.size(); i++) {
            if (arr.getString(i).equals(value) || arr.getString(i) == value) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public List<MapDivision> findByCode(String code) {
        return mapDivisionMapper.findByCode(code);
    }

    @Override
    public MapDivision mateByCode(String code) {
        // 针对某些特殊的行政区划某位只包含一个0
        int length = code.length();
        if(length % 2 == 1 && length != 9){
            code += "0";
        }
        return mapDivisionMapper.mateByCode(code);
    }

    @Override
    public List<MapDivision> listDataByCode(String code) {
        return mapDivisionMapper.listDataByCode(code);
    }

    @Override
    public String getNameByCode(String code) {
        LambdaQueryWrapper<MapDivision> condition = new QueryWrapper().lambda();
        condition.select(MapDivision::getName);
        condition.eq(MapDivision::getCode, code);
        List<MapDivision> list = list(condition);
        if(CollectionUtil.isEmpty(list)){
            return "";
        }
        return list.get(0).getName();
    }

    @Override
    public Map<String, String> mapDivisionCode2Name(List<String> divisionCodes) {
        if(CollectionUtil.isEmpty(divisionCodes)){
            return Collections.emptyMap();
        }

        LambdaQueryWrapper<MapDivision> condition = new QueryWrapper().lambda();
        condition.select(MapDivision::getName, MapDivision::getCode);
        List<MapDivision> list = list(condition);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(e -> e.getCode(), e -> e.getName(), (e1, e2) -> e2));

        return collect;
    }
}
